package dk.au.transxor.mote;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import net.tinyos.message.Message;
import dk.au.transxor.message.IMessage;

public class ContinuousFileSender extends FileSender {

	public ContinuousFileSender(int amType, int maxDataLength, MoteUart moteUart, int moteId, int sendDelay) throws FileNotFoundException {
		super(amType, maxDataLength, moteUart, moteId, sendDelay);
	}
	
	@Override
	public void sendFile(File file, boolean waitInput) {
		
		try {	
			// Read file and make messages
			List<IMessage> messages = readFile(file);
	
			if (messages != null) {
				
				BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
				String input = null;
				
				// Send every message to mote
				for (int i = 0; i < messages.size(); i++) {
					
					if(waitInput) {
						System.out.println("Send next message? (s: stop, otherwise: send)");
						input = consoleInput.readLine();
						
						if(input.equals("s")) {
							return;
						}
					}
					
					moteUart.sendMessage(moteId, (Message) messages.get(i));
					
					System.out.println(messages.get(i).get_data_seq() + ": " + new String(((IMessage) messages.get(i)).get_data_field()));
					
					try {
						Thread.sleep(sendDelay);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
	
			System.out.println("File content has been sent!");
		
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

}
